#!/bin/bash
# ===============================================
# MySQL快速部署脚本
# 一键创建数据库、表结构和示例数据
# ===============================================

echo "🚀 MySQL快速部署脚本"
echo "=================================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置参数
MYSQL_HOST=${MYSQL_HOST:-"localhost"}
MYSQL_PORT=${MYSQL_PORT:-3306}
MYSQL_USER=${MYSQL_USER:-"root"}
MYSQL_PASSWORD=${MYSQL_PASSWORD:-""}
DATABASE_NAME="mobile_data_sim"

# 函数：打印彩色信息
print_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

# 函数：检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        print_error "$1 命令未找到，请先安装"
        exit 1
    fi
}

# 函数：检查MySQL连接
check_mysql_connection() {
    print_info "检查MySQL连接..."
    
    if [ -z "$MYSQL_PASSWORD" ]; then
        mysql -h $MYSQL_HOST -P $MYSQL_PORT -u $MYSQL_USER -e "SELECT 1;" &> /dev/null
    else
        mysql -h $MYSQL_HOST -P $MYSQL_PORT -u $MYSQL_USER -p$MYSQL_PASSWORD -e "SELECT 1;" &> /dev/null
    fi
    
    if [ $? -eq 0 ]; then
        print_success "MySQL连接成功"
        return 0
    else
        print_error "MySQL连接失败"
        print_info "请检查MySQL服务状态: brew services list | grep mysql"
        print_info "启动MySQL服务: brew services start mysql"
        return 1
    fi
}

# 函数：执行MySQL命令
execute_mysql() {
    if [ -z "$MYSQL_PASSWORD" ]; then
        mysql -h $MYSQL_HOST -P $MYSQL_PORT -u $MYSQL_USER -e "$1"
    else
        mysql -h $MYSQL_HOST -P $MYSQL_PORT -u $MYSQL_USER -p$MYSQL_PASSWORD -e "$1"
    fi
}

# 函数：执行SQL文件
execute_sql_file() {
    if [ -z "$MYSQL_PASSWORD" ]; then
        mysql -h $MYSQL_HOST -P $MYSQL_PORT -u $MYSQL_USER < "$1"
    else
        mysql -h $MYSQL_HOST -P $MYSQL_PORT -u $MYSQL_USER -p$MYSQL_PASSWORD < "$1"
    fi
}

# 主函数
main() {
    print_info "开始MySQL数据库部署..."
    print_info "配置信息:"
    echo "  主机: $MYSQL_HOST:$MYSQL_PORT"
    echo "  用户: $MYSQL_USER"
    echo "  数据库: $DATABASE_NAME"
    echo ""
    
    # 1. 检查依赖
    print_info "检查依赖..."
    check_command "mysql"
    check_command "python3"
    print_success "依赖检查完成"
    
    # 2. 检查MySQL连接
    if ! check_mysql_connection; then
        exit 1
    fi
    
    # 3. 创建数据库
    print_info "创建数据库 $DATABASE_NAME..."
    execute_mysql "CREATE DATABASE IF NOT EXISTS $DATABASE_NAME CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
    if [ $? -eq 0 ]; then
        print_success "数据库创建成功"
    else
        print_error "数据库创建失败"
        exit 1
    fi
    
    # 4. 执行SQL脚本（如果存在）
    SQL_FILE="$(dirname "$0")/mysql_setup.sql"
    if [ -f "$SQL_FILE" ]; then
        print_info "执行SQL脚本: $SQL_FILE"
        execute_sql_file "$SQL_FILE"
        if [ $? -eq 0 ]; then
            print_success "SQL脚本执行成功"
        else
            print_warning "SQL脚本执行有警告"
        fi
    else
        print_warning "SQL脚本文件不存在: $SQL_FILE"
        
        # 创建基础表结构
        print_info "创建基础表结构..."
        execute_mysql "USE $DATABASE_NAME; CREATE TABLE IF NOT EXISTS user_records (id INT AUTO_INCREMENT PRIMARY KEY, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);"
    fi
    
    # 5. 使用Python脚本导入数据（如果存在）
    PYTHON_SCRIPT="$(dirname "$0")/mysql_builder.py"
    if [ -f "$PYTHON_SCRIPT" ]; then
        print_info "使用Python脚本导入示例数据..."
        python3 "$PYTHON_SCRIPT" --host $MYSQL_HOST --port $MYSQL_PORT --user $MYSQL_USER --password "$MYSQL_PASSWORD" --users 1000 --months 1
        if [ $? -eq 0 ]; then
            print_success "数据导入成功"
        else
            print_warning "数据导入失败，但数据库结构已创建"
        fi
    else
        print_warning "Python脚本不存在: $PYTHON_SCRIPT"
    fi
    
    # 6. 验证部署结果
    print_info "验证部署结果..."
    
    # 检查数据库
    DB_EXISTS=$(execute_mysql "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$DATABASE_NAME';" | grep -c $DATABASE_NAME)
    if [ $DB_EXISTS -gt 0 ]; then
        print_success "数据库存在"
    else
        print_error "数据库不存在"
    fi
    
    # 检查表
    TABLE_COUNT=$(execute_mysql "USE $DATABASE_NAME; SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '$DATABASE_NAME';" 2>/dev/null | tail -n 1)
    if [ "$TABLE_COUNT" -gt 0 ]; then
        print_success "发现 $TABLE_COUNT 个表"
        
        # 显示表列表
        print_info "数据库表列表:"
        execute_mysql "USE $DATABASE_NAME; SHOW TABLES;"
    else
        print_warning "未发现表"
    fi
    
    # 7. 显示连接信息
    print_success "部署完成！"
    echo ""
    print_info "连接信息:"
    echo "  mysql -h $MYSQL_HOST -P $MYSQL_PORT -u $MYSQL_USER -p $DATABASE_NAME"
    echo ""
    print_info "常用查询:"
    echo "  SHOW TABLES;"
    echo "  SELECT COUNT(*) FROM user_records;"
    echo "  DESCRIBE user_records;"
    echo ""
}

# 脚本参数处理
while [[ $# -gt 0 ]]; do
    case $1 in
        --host)
            MYSQL_HOST="$2"
            shift 2
            ;;
        --port)
            MYSQL_PORT="$2"
            shift 2
            ;;
        --user)
            MYSQL_USER="$2"
            shift 2
            ;;
        --password)
            MYSQL_PASSWORD="$2"
            shift 2
            ;;
        --help|-h)
            echo "使用方法: $0 [选项]"
            echo "选项:"
            echo "  --host HOST        MySQL主机地址 (默认: localhost)"
            echo "  --port PORT        MySQL端口 (默认: 3306)"
            echo "  --user USER        MySQL用户名 (默认: root)"
            echo "  --password PASS    MySQL密码 (默认: 空)"
            echo "  --help             显示此帮助信息"
            echo ""
            echo "环境变量:"
            echo "  MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASSWORD"
            exit 0
            ;;
        *)
            print_error "未知参数: $1"
            echo "使用 --help 查看帮助"
            exit 1
            ;;
    esac
done

# 执行主函数
main
